package radiostation;

import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import model.Album;
import model.Song;
import radiostation.common.AlbumRepository;

public class ArtistAlbumsUI extends BaseJFrame {

    private Album selectedAlbum;
    private final EntityManager entityManager;
    private final MainUI parent;

    public ArtistAlbumsUI(EntityManager entityManager, MainUI mainUI) {
        this.entityManager = entityManager;
        this.parent = mainUI;

        initComponents();

        // open in the center of the window
        setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        albumQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT a FROM Album a WHERE a.artist != null");
        albumList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(albumQuery.getResultList());
        jScrollPane1 = new javax.swing.JScrollPane();
        albumTable = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        albumTable.setColumnSelectionAllowed(true);
        albumTable.setName("albumTable"); // NOI18N

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, albumList, albumTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${title}"));
        columnBinding.setColumnName("Τίτλος");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${releaseDate}"));
        columnBinding.setColumnName("Ημερομηνία έκδοσης");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${artist.artisticName}"));
        columnBinding.setColumnName("Όνομα καλλιτέχνη");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${type}"));
        columnBinding.setColumnName("Τύπος");
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane1.setViewportView(albumTable);
        albumTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        jButton1.setForeground(java.awt.Color.blue);
        jButton1.setText("Νέο");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createNewGroupAlbum(evt);
            }
        });

        jButton3.setText("Επεξεργασία");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editSelectedMusicGroup(evt);
            }
        });

        jButton2.setForeground(java.awt.Color.red);
        jButton2.setText("Διαγραφή");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteSelectedMusicGroup(evt);
            }
        });

        jButton4.setText("Έξοδος");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4exitForm(evt);
            }
        });

        jLabel1.setText("Διαχείριση άλμπουμ καλλιτεχνών");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 830, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton4)
                        .addContainerGap())))
            .addGroup(layout.createSequentialGroup()
                .addGap(300, 300, 300)
                .addComponent(jLabel1)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 479, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton1)
                            .addComponent(jButton3)
                            .addComponent(jButton2))
                        .addContainerGap(39, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton4)
                        .addContainerGap())))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void createNewGroupAlbum(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createNewGroupAlbum

        selectedAlbum = new Album(null);
        selectedAlbum.setType("CS");
        selectedAlbum.setSongList(new ArrayList<>());

        try {

            ArtistAlbumsEditUI artistAlbumsEditUI = new ArtistAlbumsEditUI(selectedAlbum, entityManager);
            artistAlbumsEditUI.setVisible(true);
            setEnabled(false);

            artistAlbumsEditUI.addWindowListener(new WindowListener() {
                public void windowClosed(WindowEvent arg0) {
                    if (((MyWindowEvent) arg0).exitAndSave) {

                        if (!entityManager.getTransaction().isActive()) {
                            entityManager.getTransaction().begin();
                        }

                        // persist in db
                        entityManager.persist(selectedAlbum);
                        entityManager.flush();

                        // add the artist in the list
                        albumList.add(selectedAlbum);

                        // select artist in table list
                        int row = albumList.size() - 1;
                        albumTable.setRowSelectionInterval(row, row);
                        albumTable.scrollRectToVisible(albumTable.getCellRect(row, 0, true));

                        // commit transaction
                        entityManager.getTransaction().commit();
                    }

                    // enable current form
                    setEnabled(true);
                }

                public void windowActivated(WindowEvent arg0) {
                }

                public void windowClosing(WindowEvent arg0) {
                }

                public void windowDeactivated(WindowEvent arg0) {
                }

                public void windowDeiconified(WindowEvent arg0) {
                }

                public void windowIconified(WindowEvent arg0) {
                }

                public void windowOpened(WindowEvent arg0) {
                }
            });

        } catch (Exception e) {
            Exception eχ = e;
            throw e;
        }
    }//GEN-LAST:event_createNewGroupAlbum

    private void editSelectedMusicGroup(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editSelectedMusicGroup
        // check if music group is selected

        int row = albumTable.getSelectedRow();

        if (row == -1) {
            showWarningMessage("Δεν έχει επιλεχθεί άλμπουμ");
            return;
        }

        selectedAlbum = albumList.get(row);

        try {
            ArtistAlbumsEditUI artistAlbumsEditUI = new ArtistAlbumsEditUI(selectedAlbum, entityManager);
            artistAlbumsEditUI.setVisible(true);
            setEnabled(false);

            artistAlbumsEditUI.addWindowListener(new WindowListener() {
                public void windowClosed(WindowEvent arg0) {

                    if (((MyWindowEvent) arg0).exitAndSave) {

                        try {
                            if (!entityManager.getTransaction().isActive()) {
                                entityManager.getTransaction().begin();
                            }
                            AlbumRepository albumRepository = new AlbumRepository(entityManager);
                            Album stateAlbum = albumRepository.findById(selectedAlbum.getAlbumId());

                            //replace current table row with the new one
                            albumList.set(row, stateAlbum);

                            albumTable.setRowSelectionInterval(row, row);
                            albumTable.scrollRectToVisible(albumTable.getCellRect(row, 0, true));

                            // commit transaction
                            entityManager.getTransaction().commit();
                        } catch (Exception e) {
                            entityManager.getTransaction().rollback();
                        }
                    }
                    // enable the current form
                    setEnabled(true);
                }

                public void windowActivated(WindowEvent arg0) {
                }

                public void windowClosing(WindowEvent arg0) {
                }

                public void windowDeactivated(WindowEvent arg0) {
                }

                public void windowDeiconified(WindowEvent arg0) {
                }

                public void windowIconified(WindowEvent arg0) {
                }

                public void windowOpened(WindowEvent arg0) {
                }
            });

        } catch (Exception e) {
            Exception eχ = e;
            throw e;
        }
    }//GEN-LAST:event_editSelectedMusicGroup

    private void deleteSelectedMusicGroup(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteSelectedMusicGroup

        // check if selected album exists
        int row = albumTable.getSelectedRow();

        if (row == -1) {
            showWarningMessage("Δεν έχει επιλεγεί άλμπουμ");
            return;
        }

        // prompt delete
        int choice = showPrompt("Διαγραφή συγκροτήματος;", "Επιβεβαίωση διαγραφής συγκροτήματος");

        if (choice != 0) {
            return;
        }

        // get album to delete
        Album albumToRemove = albumList.get(row);

        if (!entityManager.getTransaction().isActive()) {
            entityManager.getTransaction().begin();
        }

        albumToRemove.getMusicGroup().getAlbumList().remove(albumToRemove);

        //remove album from company's list
        albumToRemove.getCompany().getAlbumList().remove(albumToRemove);

        // remove album's songs
        albumToRemove.getSongList().stream().forEach((s) -> {
            entityManager.remove(s);
        });

        // remove music group from db
        entityManager.remove(albumToRemove);

        // remove music group from list that used for binding
        albumList.remove(albumToRemove);

        // commit transation
        entityManager.getTransaction().commit();

    }//GEN-LAST:event_deleteSelectedMusicGroup

    private void jButton4exitForm(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4exitForm

        // enable parent form
        parent.setEnabled(true);
        // close current form and destroy all the attached resources
        dispose();
    }//GEN-LAST:event_jButton4exitForm


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.util.List<model.Album> albumList;
    private javax.persistence.Query albumQuery;
    private javax.swing.JTable albumTable;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
